package com.example.finalhomework.cardgame.viewmodel

import android.content.Context
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.lifecycle.ViewModel
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.example.cardgame.model2.CardMatchingGame
import com.example.finalhomework.cardgame.ui.loadUserInfo
import com.example.finalhomework.cardgame.ui.saveUserInfo

class AdvancedCardGameViewModel : ViewModel() {
    // 初始化游戏对象，包含24张卡片
    var game: CardMatchingGame = CardMatchingGame(24)
    // 使用可变状态保存当前分数
    var score by mutableStateOf(game.score)

    init {
        Log.d("AdvancedCardGameViewModel", "Game initialized with score: $score")
    }

    // 选择指定索引的卡片
    fun chooseCardAtIndex(index: Int) {
        Log.d("AdvancedCardGameViewModel", "Card chosen at index: $index")
        game.chooseCardAtIndex(index)
        // 更新分数
        score = game.score
        Log.d("AdvancedCardGameViewModel", "Score updated to: $score")
    }

    // 重置游戏
    fun resetGame() {
        Log.d("AdvancedCardGameViewModel", "Game reset")
        game.reset()
        // 重置分数
        score = game.score
        Log.d("AdvancedCardGameViewModel", "Score reset to: $score")
    }

    fun updateHighestScore(context: Context) {
        Log.d("AdvancedCardGameViewModel", "Updating highest score")
        // 加载用户信息
        val userInfo = loadUserInfo(context)
        Log.d("AdvancedCardGameViewModel", "Loaded user info: $userInfo")
        // 如果当前分数大于用户的最高高级分数，则更新用户信息
        if (score > userInfo.advancedHighestScore) {
            Log.d("AdvancedCardGameViewModel", "New highest score: $score")
            // 创建一个更新后的用户信息对象，包含新的最高高级分数
            val updatedUserInfo = userInfo.copy(advancedHighestScore = score)
            // 保存更新后的用户信息
            saveUserInfo(context, updatedUserInfo)
            Log.d("AdvancedCardGameViewModel", "User info updated with new highest score: $updatedUserInfo")
        }
    }
}